﻿#region Imports
using System.Windows.Forms;
using CommonUtilities.Extensions;
using CommonUtilities.Util;
#endregion

namespace CommonUtilities.Controls
{
    /// <summary>
    /// CommonUtilities DataGridView
    /// (inherited from System.Windows.Forms.DataGridView)
    /// </summary>
    public class CUtil_DataGridView : DataGridView
    {
        #region Declarations
        public event DataGridViewCellEventHandler CellMouseLeave;
        public event DataGridViewCellMouseEventHandler CellMouseClick;
        public event DataGridViewCellMouseEventHandler CellMouseMove;
        #endregion

        #region Properties
        /// <summary>
        /// Specifies if <code>System.Windows.Forms.DataGridViewLinkCell</code> 
        /// should use customized behaviour as defined in <code>CommonUtilities.Controls.CUtil_DataGridView</code>
        /// </summary>
        public bool UseSpecialLinkBehaviour { get; set; }
        #endregion

        #region Constructors
        public CUtil_DataGridView()
            : base()
        {
            UseSpecialLinkBehaviour = true;

            base.CellMouseLeave += new DataGridViewCellEventHandler(DataGridView_CellMouseLeave);
            base.CellMouseClick += new DataGridViewCellMouseEventHandler(DataGridView_CellMouseClick);
            base.CellMouseMove += new DataGridViewCellMouseEventHandler(DataGridView_CellMouseMove);
        }
        #endregion

        #region Events
        private void DataGridView_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 || e.ColumnIndex == -1) return;

            Cursor = Cursors.Default;

            if (!this.CellMouseLeave.IsNull())
                this.CellMouseLeave(sender, e);
        }

        private void DataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex == -1 || e.ColumnIndex == -1) return;

            if (UseSpecialLinkBehaviour)
            {
                DataGridView dgView = (DataGridView)sender;
                if (dgView.Columns[e.ColumnIndex].CellType == (typeof(DataGridViewLinkCell)))
                    Utilities.OpenPath(dgView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
            }

            if (!this.CellMouseClick.IsNull())
                this.CellMouseClick(sender, e);
        }

        private void DataGridView_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex == -1 || e.ColumnIndex == -1) return;

            DataGridView dgView = (DataGridView)sender;
            Cursor = (dgView.Columns[e.ColumnIndex].CellType == (typeof(DataGridViewLinkCell)))
                ? Cursors.Hand : Cursors.Default;

            if (!this.CellMouseMove.IsNull())
                this.CellMouseMove(sender, e);
        }
        #endregion
    }
}
